//
//  DIYKVO.m
//  TableViewTestDemo
//
//  Created by 张蒙召 on 2021/1/15.
//  Copyright © 2021 张蒙召. All rights reserved.
//

#import "DIYKVO.h"

typedef void(^kvoBlock)(id object,NSString *keypath);

@interface DIYKVO ()
@property (nonatomic, strong)  id object;
@property (nonatomic, strong)  NSString *keypath;
@property (nonatomic, copy) kvoBlock block;



@end

@implementation DIYKVO

- (instancetype)initWithObject:(id)obj ForKeyPath:(NSString *)keypath handler:(void (^)(id object,NSString *keypath))block {
    
    self.object = obj;
    self.keypath = keypath;
    [obj addObserver:self forKeyPath:keypath options:NSKeyValueObservingOptionNew context:NULL];
    return self;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:self.keypath]) {
          if (self.block) {
              self.block(self.object, self.keypath);
          }
    }
}
- (void)dealloc {
    NSLog(@"%s",__func__);
    if (self.object) {
        [self.object removeObserver:self forKeyPath:self.keypath];
    }
}
@end
